#!/bin/bash
# data: 2022/11/24
# auth: fearless11
# desc: install pushgateway
# doc: https://github.com/prometheus/pushgateway
# https://www.cnblogs.com/xiao987334176/p/9933963.html

ip_local=$(/usr/sbin/ip add | grep inet | grep global | grep -Ev 'docker' | awk '{print $2}' | awk -F/ '{print $1}' | tail -1)
port=9091
addr=${ip_local}:${port}
docker_name="pushgateway_${port}"
image="prom/pushgateway:v1.4.3"
data=$(pwd)/data

docker_start() {
  docker run -d --name ${docker_name} \
    -m 512m \
    --net=host \
    --restart=always \
    --log-opt max-size=100m \
    --log-opt max-file=10 \
    -u root \
    -v ${data}/pushgateway:/data \
    ${image} \
    --web.enable-admin-api \
    --persistence.file="/data/pushmetrics" \
    --persistence.interval=1m
}

docker_stop() {
  docker stop ${docker_name}
  docker rm ${docker_name}
}


docker_exec() {
  docker exec -it ${docker_name} sh
}

docker_logs() {
  docker logs --tail=10 ${docker_name}
}

send_metric() {
  echo "test_metric 6.99" | curl --data-binary @- http://${addr}/metrics/job/pushgateway
}

send_metrics() {
  cat <<EOF | curl --data-binary @- http://${addr}/metrics/job/some_job/instance/some_instance
# TYPE some_metric counter
test_metric{label="val1"} 42
# TYPE another_metric gauge
# HELP another_metric Just an example.
two_metric 2398.283
EOF
}

query_status() {
  curl -s -XGET http://${addr}/api/v1/status | python -m json.tool
}

query_metrics() {
  curl -s -X GET http://${addr}/api/v1/metrics | python -m json.tool
}

set_admin() {
  curl -XPUT http://${addr}/api/v1/admin/wipe
}


case $1 in
start)
  docker_start
  ;;
stop)
  docker_stop
  ;;
exec)
  docker_exec
  ;;
logs)
  docker_logs
  ;;
send)
  send_metric
  ;;
sends)
  send_metrics
  ;;
status)
  query_status
  ;;
metrics)
  query_metrics
  ;;
admin)
  set_admin
  ;;
*)
  echo "start|stop|exec|logs|send|sends|status|metrics|admin"
  ;;
esac
